package org.jeecg.modules.wlhy.hycarrier.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.paycenter.channel.bankdocking.dto.Acc;
import org.jeecg.modules.paycenter.channel.bankdocking.service.NhBankService;
import org.jeecg.modules.paycenter.service.WalletService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.hycarrier.entity.HyCarrier;
import org.jeecg.modules.wlhy.hycarrier.entity.HyCarrierAccountBook;
import org.jeecg.modules.wlhy.hycarrier.entity.HyCarrierBank;
import org.jeecg.modules.wlhy.hycarrier.service.IHyCarrierAccountBookService;

import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.wlhy.hycarrier.service.IHyCarrierBankService;
import org.jeecg.modules.wlhy.hycarrier.service.IHyCarrierService;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: hy_carrier_account_book
 * @Author: jeecg-boot
 * @Date:   2022-08-05
 * @Version: V1.0
 */
@Api(tags="hy_carrier_account_book")
@RestController
@RequestMapping("/hycarrier/hyCarrierAccountBook")
@Slf4j
public class HyCarrierAccountBookController extends JeecgController<HyCarrierAccountBook, IHyCarrierAccountBookService> {
	@Autowired
	private IHyCarrierAccountBookService hyCarrierAccountBookService;

	@Autowired
	private IHyCarrierService hyCarrierService;

	@Autowired
	private NhBankService nhBankService;

	 @Autowired
	 private UserUtil userUtil;

	 @Autowired
	 private IHySettingService settingService;

	 @Autowired
	 private WalletService walletService;

	 @Autowired
	 private IHyCarrierBankService hyCarrierBankService;

	 @Value("${pay-config.trade.begin:8}")
	 private String TRADE_BEGIN;

	 @Value("${pay-config.trade.end:19}")
	 private String TRADE_END;

	 @Value("${pay-config.cash-out.active:1}")
	 private String CASHOUT_ACTIVE;

	 @Value("${pay-config.cash-out.begin:8}")
	 private String CASHOUT_BEGIN;

	 @Value("${pay-config.cash-out.end:19}")
	 private String CASHOUT_END;

	 @Value("${pay-config.sms-active:0}")
	 private String CASH_OUT_SMS_ACTIVE;

	 @Value("${pay-config.acc-sms-active:0}")
	 private String ACC_SMS_ACTIVE;


//	@ApiOperation(value="hy_carrier_account_book-分页列表查询", notes="hy_carrier_account_book-分页列表查询")
//	@GetMapping(value = "/list")
//	public Result<?> queryPageList(HyCarrierAccountBook hyCarrierAccountBook,
//								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
//								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
//								   HttpServletRequest req) {
//		QueryWrapper<HyCarrierAccountBook> queryWrapper = QueryGenerator.initQueryWrapper(hyCarrierAccountBook, req.getParameterMap());
//		Page<HyCarrierAccountBook> page = new Page<HyCarrierAccountBook>(pageNo, pageSize);
//		IPage<HyCarrierAccountBook> pageList = hyCarrierAccountBookService.page(page, queryWrapper);
//		return Result.OK(pageList);
//	}
	

	 @ApiOperation(value="获取车队长多级账簿信息", notes="获取车队长多级账簿信息")
	 @GetMapping(value = "/getAccountBookInfo")
//	 @RequiresPermissions("driver:getAccountBook")
	 public Result<?> getAccountBookInfo(String carrierId) {
		 if(StringUtils.isEmpty(carrierId)){
			 return Result.error("车队长信息不存在");
		 }
		 HyCarrierAccountBook accountBook = hyCarrierAccountBookService.getAccountBookByCarrierId(carrierId);
		 if(accountBook == null){
			 return Result.OK(null);
		 }
		 if(!userUtil.isSys()){
			 HyCustomer customer = userUtil.getCustomer();
			 if(customer == null){
				 return Result.error("货主信息不存在");
			 }
			 if(!StringUtils.equals(customer.getId() , accountBook.getCustomerId())){
				 return Result.error("信息不存在");
			 }
		 }
		 nhBankService.getCarriderAccBookInfo(accountBook);
		 return Result.OK(accountBook);
	 }

	 @AutoLog(value = "开通车队长钱包")
	 @ApiOperation(value="开通车队长钱包", notes="开通车队长钱包")
	 @PostMapping(value = "/addAccountBook")
//	 @RequiresPermissions("driver:addAccountBook")
	 public Result<?> addAccountBook(@RequestBody Map<String,String> params) {
		 if (DateUtil.hour(new Date(), true)>Integer.parseInt(TRADE_END) || DateUtil.hour(new Date(), true) < Integer.parseInt(TRADE_BEGIN)){
			 return Result.error("不在交易时间内, 详情请咨询系统管理员！");
		 }

		 HyConfig config = HyConfigUtils.getConfig();
		 if(!config.getNhbankIzUse()){
			 return Result.error("未开通服务！");
		 }

		 String carrierId = params.get("carrierId");
		 if(StringUtils.isEmpty(carrierId)){
			 return Result.error("车队长信息不存在");
		 }
		 //是否开通过
		 HyCarrierAccountBook accountBook = hyCarrierAccountBookService.getAccountBookByCarrierId(carrierId);
		 if(accountBook != null){
			 return Result.error("不能重复开通");
		 }

		 HyCarrier carrier = hyCarrierService.getById(carrierId);
		 if(carrier == null){
			 return Result.error("车队长信息不存在");
		 }

		 if(!userUtil.isSys()){
			 HyCustomer customer = userUtil.getCustomer();
			 if(customer == null){
				 return Result.error("货主信息不存在");
			 }
			 if(!StringUtils.equals(customer.getId() , carrier.getCustomerId())){
				 return Result.error("车队长信息不存在");
			 }
		 }
		 nhBankService.addCarrierAccountBook(carrier);
		 return Result.OK("开通成功！");
	 }

	 @AutoLog(value = "车队长提现")
	 @ApiOperation(value="车队长提现", notes="车队长提现")
	 @PostMapping(value = "/tx")
	 public Result<?> tx(@RequestBody JSONObject jsonObject) {
		 if ("1".equalsIgnoreCase(CASHOUT_ACTIVE)
				 &&( DateUtil.hour(new Date(), true)>Integer.parseInt(CASHOUT_END) || DateUtil.hour(new Date(), true) <Integer.parseInt(CASHOUT_BEGIN))){
			 return Result.error("不在交易时间内, 详情请咨询系统管理员！");
		 }
		 HyConfig config = HyConfigUtils.getConfig();
		 if (!config.getNhbankIzUse()) {
			 return Result.error("未开通服务！");
		 }

		 String settingValue = settingService.getSettingValueByTag2("bank_relative");
		 if(!"1".equals(settingValue)) {
			 return Result.error("系统暂时关闭支付功能！");
		 }

		 String pwd = jsonObject.getString("pwd");
		 String bankId = jsonObject.getString("bankId");
		 String samt = jsonObject.getString("amt");
		 String carrierId = jsonObject.getString("carrierId");

		 if(StringUtils.isEmpty(pwd)){
			 return Result.error("支付密码不能为空！");
		 }
		 HyCarrierBank carrierBank = null;
		 if(!StringUtils.isEmpty(bankId)){
			 carrierBank = hyCarrierBankService.getById(bankId);
			 if(carrierBank == null){
				 return Result.error("银行卡信息不存在！");
			 }
			 if(!StringUtils.equals(carrierBank.getCarrierId() , carrierId)){
				 return Result.error("银行卡信息不存在！");
			 }
		 }

		 if(StringUtils.isEmpty(samt)){
			 return Result.error("提现金额不能为空！");
		 }
		 BigDecimal amt = null;
		 try{
			 amt = new BigDecimal(samt);
		 }catch (Exception e){
			 return Result.error("提现金额格式错误！");
		 }
		 // 0 > amt
		 if(BigDecimal.ZERO.compareTo(amt) == 1){
			 return Result.error("提现金额错误！");
		 }
		 HyCarrier carrier = hyCarrierService.getById(carrierId);
		 if(carrier == null){
			 return Result.error("车队长信息不存在");
		 }
		 HyCarrierAccountBook carrierAccountBook = hyCarrierAccountBookService.getAccountBookByCarrierId(carrierId);
		 if(carrierAccountBook == null){
			 return Result.error("车队长钱包不存在");
		 }
		 boolean isSys = userUtil.isSys();
		 HyCustomer customer = null;
		 if(isSys){
			 if(!walletService.checkPwd(pwd)){
				 return Result.error("支付密码错误");
			 }
		 }else {
			 customer = userUtil.getCustomer();
			 if(customer==null){
				 return Result.error("货主信息不存在!");
			 }
			 if(!StringUtils.equals(carrierAccountBook.getCustomerId(), customer.getId())){
				 return Result.error("钱包信息错误!");
			 }
			 if(!walletService.checkPwd(pwd)){
				 return Result.error("支付密码错误");
			 }
		 }

		 Acc acc = nhBankService.getAccBookInfo(carrierAccountBook.getAccNo(), carrierAccountBook.getLogAccNo(), carrierAccountBook.getProv());
		 if(acc == null){
			 return Result.error("查询余额失败");
		 }
		 //可用余额
		 BigDecimal availBal = acc.getAvailBal();
		 if (amt.compareTo(availBal) == 1) {
			 return Result.error("账户余额不足");
		 }
		 //提现
		 Result result = nhBankService.carrierTx(carrierAccountBook, carrier, amt , carrierBank);
		 return result;
	 }

//	 @AutoLog(value = "hy_carrier_account_book-添加")
//	 @ApiOperation(value="hy_carrier_account_book-添加", notes="hy_carrier_account_book-添加")
//	 @PostMapping(value = "/add")
//	 public Result<?> add(@RequestBody HyCarrierAccountBook hyCarrierAccountBook) {
//		 hyCarrierAccountBookService.save(hyCarrierAccountBook);
//		 return Result.OK("添加成功！");
//	 }
//
//
//	 @AutoLog(value = "hy_carrier_account_book-编辑")
//	 @ApiOperation(value="hy_carrier_account_book-编辑", notes="hy_carrier_account_book-编辑")
//	 @PutMapping(value = "/edit")
//	 public Result<?> edit(@RequestBody HyCarrierAccountBook hyCarrierAccountBook) {
//		 hyCarrierAccountBookService.updateById(hyCarrierAccountBook);
//		 return Result.OK("编辑成功!");
//	 }
//
//
//	 @AutoLog(value = "hy_carrier_account_book-通过id删除")
//	 @ApiOperation(value="hy_carrier_account_book-通过id删除", notes="hy_carrier_account_book-通过id删除")
//	 @DeleteMapping(value = "/delete")
//	 public Result<?> delete(@RequestParam(name="id",required=true) String id) {
//		 hyCarrierAccountBookService.removeById(id);
//		 return Result.OK("删除成功!");
//	 }
//	/**
//	 *  批量删除
//	 *
//	 * @param ids
//	 * @return
//	 */
//	@AutoLog(value = "hy_carrier_account_book-批量删除")
//	@ApiOperation(value="hy_carrier_account_book-批量删除", notes="hy_carrier_account_book-批量删除")
//	@DeleteMapping(value = "/deleteBatch")
//	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
//		this.hyCarrierAccountBookService.removeByIds(Arrays.asList(ids.split(",")));
//		return Result.OK("批量删除成功!");
//	}
//
//	/**
//	 * 通过id查询
//	 *
//	 * @param id
//	 * @return
//	 */
//	@ApiOperation(value="hy_carrier_account_book-通过id查询", notes="hy_carrier_account_book-通过id查询")
//	@GetMapping(value = "/queryById")
//	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
//		HyCarrierAccountBook hyCarrierAccountBook = hyCarrierAccountBookService.getById(id);
//		if(hyCarrierAccountBook==null) {
//			return Result.error("未找到对应数据");
//		}
//		return Result.OK(hyCarrierAccountBook);
//	}
//
//    /**
//    * 导出excel
//    *
//    * @param request
//    * @param hyCarrierAccountBook
//    */
//    @RequestMapping(value = "/exportXls")
//    public ModelAndView exportXls(HttpServletRequest request, HyCarrierAccountBook hyCarrierAccountBook) {
//        return super.exportXls(request, hyCarrierAccountBook, HyCarrierAccountBook.class, "hy_carrier_account_book");
//    }
//
//    /**
//      * 通过excel导入数据
//    *
//    * @param request
//    * @param response
//    * @return
//    */
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//        return super.importExcel(request, response, HyCarrierAccountBook.class);
//    }

}
